package com.micro.play.internet.audio.book.domain.service.impl;

import com.google.common.collect.Maps;
import com.micro.play.internet.audio.book.domain.pojo.em.WebsiteType;
import com.micro.play.internet.audio.book.domain.service.BaseService;
import com.micro.play.internet.audio.book.domain.service.IPlayService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author guochaohui
 * @return
 * @date 2020-03-02 16:13
 */
@Service
public class PlayServiceAdapter extends BaseService implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Map<WebsiteType, IPlayService> serviceMap;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (serviceMap != null && !serviceMap.isEmpty()) {
            return;
        }
        serviceMap = Maps.newHashMap();
        Map<String, IPlayService> beans = applicationContext.getBeansOfType(IPlayService.class);
        if (beans.isEmpty()) {
            throw new RuntimeException("No impl beans defined.");
        }
        beans.forEach((key, impl) -> serviceMap.put(impl.websiteType(), impl));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public IPlayService getService(WebsiteType websiteType) {
        return serviceMap.get(websiteType);
    }
}
